<template>
  <div class="chat-msg-box" ref="chatMsgRef">
    <div class="chat-item-box" v-for="(item, index) in curSession?.messages" :key="index">
      <div class="chat-msg">
        <template v-if="item.role === 'assistant'">
          <div class="ai-msg">
            <div class="mr-8">
              <img src="@/assets/images/system.svg" width="32" height="32" alt="" />
            </div>
            <div class="preset-box" v-if="item.isPreQue">
              <van-tabs v-model:active="item.activeTab" @change="tabChange" shrink>
                <van-tab v-for="tab in item.tabs" :key="tab.id" :title="tab.title" :name="tab.id">
                  <div v-if="tab.quesList.length > 0">
                    <ul class="q-list">
                      <li
                        class="q-item"
                        v-for="que in tab.quesList"
                        :key="que.id"
                        @click="handlePreQueClick(que)"
                      >
                        <p class="q-inten">{{ que.question }}</p>
                        <van-icon name="arrow" />
                      </li>
                    </ul>
                    <div class="more" v-if="tab.total > tab.quesList.length" @click="loadMore(tab)">
                      <van-loading type="spinner" v-if="loading" size="20px" />
                      加载更多
                    </div>
                  </div>
                  <van-empty v-else description="当前无数据" />
                </van-tab>
              </van-tabs>
            </div>
            <div flex="dir:top" v-else>
              <div class="ai-btn">
                <div flex="main:left cross:center">
                  <van-button size="mini" @click="copyMsg(item)" title="复制">
                    <div class="icon-box">
                      <img src="@/assets/images/copy.svg" alt="" width="14" height="14" />
                    </div>
                  </van-button>
                  <van-button size="mini" @click="removeMsg(index)" title="删除">
                    <div class="icon-box">
                      <img src="@/assets/images/delete.svg" alt="" width="14" height="14" />
                    </div>
                  </van-button>
                  <van-button
                    size="mini"
                    v-show="item.feedbackResult !== 'BAD'"
                    :type="item.feedbackResult === 'GOOD' ? 'primary' : 'default'"
                    @click="handlePraiseMsg(item)"
                    title="赞"
                  >
                    <div class="icon-box">
                      <img
                        src="@/assets/images/praise.svg"
                        alt=""
                        width="14"
                        height="14"
                        :class="{ icon: item.feedbackResult === 'GOOD' }"
                      />
                    </div>
                  </van-button>
                  <van-button
                    size="mini"
                    v-show="item.feedbackResult !== 'GOOD'"
                    :type="item.feedbackResult === 'BAD' ? 'danger' : 'default'"
                    @click="handleTrampleMsg(item)"
                    title="踩"
                  >
                    <div class="icon-box">
                      <img
                        src="@/assets/images/trample.svg"
                        alt=""
                        width="14"
                        height="14"
                        :class="{ icon: item.feedbackResult === 'BAD' }"
                      />
                    </div>
                  </van-button>
                </div>
              </div>
              <div class="msg-con">
                <template v-if="curSession.msgLoading && index === curSession.messages.length - 1">
                  <div flex="cross:center">
                    <van-loading type="spinner" size="20px" />
                    <span style="color: #86929e; margin-left: 5px">知识库搜索中...</span>
                  </div>
                </template>
                <template v-else>
                  <v-md-preview :text="item.content" />
                  <van-tag
                    v-if="index > 0 && item.cited?.length > 0"
                    type="primary"
                    no-border
                    style="cursor: pointer"
                    @click="handleViewCited(item.cited)"
                  >
                    {{ item.cited.length }}条引用
                  </van-tag>
                </template>
              </div>
            </div>
          </div>
        </template>

        <template v-else>
          <div class="user-msg">
            <div flex="dir:top">
              <div class="msg-btn">
                <div flex="main:right cross:center">
                  <van-button size="mini" @click="copyMsg(item)" title="复制">
                    <div class="icon-box">
                      <img src="@/assets/images/copy.svg" alt="" width="14" height="14" />
                    </div>
                  </van-button>
                  <van-button size="mini" @click="repeatMsg(item)" title="重发">
                    <div class="icon-box">
                      <img src="@/assets/images/rebuild.svg" alt="" width="14" height="14" />
                    </div>
                  </van-button>
                  <van-button size="mini" @click="removeMsg(index)" title="删除">
                    <div class="icon-box">
                      <img src="@/assets/images/delete.svg" alt="" width="14" height="14" />
                    </div>
                  </van-button>
                </div>
              </div>
              <div class="msg-con">
                {{ item.content }}
              </div>
            </div>
            <img class="avatar" :src="headImgUrl" width="32" height="32" alt="" />
          </div>
        </template>
      </div>
    </div>

    <van-dialog v-model:show="open" title="查看引用数据">
      <div v-if="open" class="cited-info-con">
        <div v-for="(item, index) in citedInfo" :key="index">
          <div class="item">
            <div class="t-right f-s-12">
              距离：
              <van-tag type="primary">{{ item.distance }}</van-tag>
            </div>
            <div class="ref">
              <v-md-preview :text="item.text" />
            </div>
          </div>
        </div>
      </div>
    </van-dialog>
    <FeeBackModal
      v-model="openFeeback"
      :feebackParams="feebackParams"
      :shareId="shareId"
      @success="feebackSuccess"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { throwError } from '@/utils/util'
import { savePreRecord, userFeedback } from '@/api/modules/home.api'
import { useUserStore } from '@/store/useUserStore'
import { showNotify } from 'vant'

import {
  chatMsgRef,
  curSession,
  msgChangeScrollToBottom,
  saveSessions,
  copyMsg,
  repeatMsg,
  removeMsg,
} from './useChat'
import FeeBackModal from './FeeBackModal.vue'
import { v4 } from 'uuid'

const emit = defineEmits(['tabChange', 'loadMore'])

const userStore = useUserStore()
console.log('获取的用户信息===============', userStore.userInfo)

const headImgUrl = computed(() => userStore.userInfo?.headImgUrl || getImageUrl('user'))

const props = defineProps({
  shareId: {
    type: String,
    default: '',
  },
  loading: {
    type: Boolean,
    default: false,
  },
})

const open = ref(false)
const citedInfo = ref([])
const openFeeback = ref(false)
const feebackParams = ref({})

function getImageUrl(name) {
  return new URL(`../../assets/images/${name}.svg`, import.meta.url).href
}

onMounted(() => {
  msgChangeScrollToBottom()
})

// 一级分类切换查询对应的预设问题
function tabChange(tab) {
  emit('tabChange', tab)
}

// 查看引用
function handleViewCited(cited) {
  citedInfo.value = cited
  open.value = true
}

// 预设问题点击
async function handlePreQueClick(item) {
  curSession.value.messages.push(
    {
      role: 'user',
      content: item.question,
      chatItemId: v4().replaceAll('-', ''),
    },
    {
      role: 'assistant',
      content: item.answer,
      answerChatItemId: v4().replaceAll('-', ''),
    },
  )
  // 保存预设问题的日志记录
  const index = curSession.value.messages.findLastIndex(
    i => i.content === item.question || i.content === item.answer,
  )

  const params = {
    answerIndex: index + 1, // 答案的索引
    answer: item.answer,
    question: item.question,
    answerChatItemId: curSession.value.messages[index].answerChatItemId, // 回答的ID
    chatItemId: curSession.value.messages[index - 1].chatItemId, // 问题的ID
    chatId: curSession.value.id, // 会话id
    index: index, // 问题的索引
  }
  await savePreRecord(props.shareId, params)
}

// 加载更多
async function loadMore(id) {
  emit('loadMore', id)
}

// 点赞
async function handlePraiseMsg(item) {
  feebackParams.value = {
    id: item.answerChatItemId,
    feedbackResult: item.feedbackResult !== 'GOOD' ? 'GOOD' : '',
    feedbackMsg: '',
  }
  try {
    await userFeedback(props.shareId, feebackParams.value)
    showNotify({ type: 'success', message: '操作成功' })
    open.value = false
  } catch (e) {
    throwError('ChatMsgNew/handlePraiseMsg', e)
  }
  updateSessions(item)
}

// 用户反馈
async function handleTrampleMsg(item) {
  feebackParams.value = {
    id: item.answerChatItemId,
    feedbackResult: item.feedbackResult !== 'BAD' ? 'BAD' : '',
    feedbackMsg: '',
  }
  if (item.feedbackResult === 'BAD') {
    try {
      await userFeedback(props.shareId, feebackParams.value)
    } catch (e) {
      throwError('ChatMsgNew/handleTrampleMsg', e)
    }
    updateSessions(item)
  } else {
    openFeeback.value = true
  }
}

function feebackSuccess(data) {
  const params = {
    answerChatItemId: data.id,
  }
  updateSessions(params)
}

// 更新Sessions
function updateSessions(item) {
  let messages = curSession.value.messages.map(obj => {
    if (obj.role === 'assistant' && obj.answerChatItemId === item.answerChatItemId) {
      return { ...obj, feedbackResult: feebackParams.value.feedbackResult, feedbackMsg: '' }
    } else {
      return obj
    }
  })
  curSession.value.messages = messages
  saveSessions([curSession.value])
}
</script>

<style lang="stylus" scoped>
.mr-8{
  margin-right 8px;
}
.chat-msg-box {
  height: calc(100% - 50px);
  width: 800px;
  flex: 1;
  overflow-y: auto;

  .chat-item-box {
    width: 100%;
    height: auto;

    :deep(.van-button) {
      width: 6vw
      height: 6vw
      border-radius 8px;
    }

    .chat-msg {
      margin: 0 auto;
      min-width: 90%;

      .ai-msg {
        display: flex;
        padding: 16px 0;
        background-color: #fff;
        word-wrap: break-word;
        position: relative;

        .ai-btn {
          display: block;
          .icon-box{
            overflow hidden;
            .icon{
              filter: drop-shadow(#fff 100px 0);
              transform: translateX(-100px);
            }
          }
        }

        .msg-con {
          padding: 8px 10px;
          border-radius: 0px 8px 8px;
          box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 8px;
          margin-right 20px;
        }
      }

      .user-msg {
        display: flex;
        justify-content: flex-end;
        padding: 16px;
        word-wrap: break-word;
        position: relative;

        .msg-con {
          padding: 10px;
          border-radius: 8px 0px 8px 8px;
          box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 8px;
          background: #cfe7ff;
          margin-left 42px;
        }

        .msg-btn {
          display: block;
        }
      }

      .avatar{
        border-radius 50%;
        margin-left 5px;
      }

      .icon-size {
        font-size: 20px;
      }

      .msg-con {
        display: inline-block;
        word-wrap: break-word;
        margin-top: 5px;
      }

      :deep(.vuepress-markdown-body) {
        padding: 0;
        font-size: 14px;
      }
    }

  }

  .cited-info-con {
    max-height: 400px;
    overflow-y: auto;

    .item {
      margin: 8px;

      .ref {
        margin-top: 4px;
        padding: 8px;
        border: 1px solid rgba(0, 0, 0, 0.08);
      }
    }

    :deep(.vuepress-markdown-body) {
      padding: 0;
      font-size: 14px;
    }
  }
}

.preset-box {
  width 84%;
  border-radius: 8px;
  box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 8px;

  .q-list {
    padding 10px 20px;
    min-height 134px;

    .q-item {
      display flex;
      align-items: center;
      justify-content: space-between;
      cursor pointer;
      padding 5px 0;
      height 24px;
      border-bottom: 1px solid #e3e5e7;

      &:not(:last-child) {
        // border-bottom: 1px solid #e3e5e7;
      }
    }
  }
  .more{
    display flex;
    align-items center;
    justify-content center;
    padding 0 10px 10px 10px;
    cursor pointer;
    color: #aeb6bf;
  }
}
</style>
